﻿using System;
using System.Configuration;
using System.Data.SqlClient;

namespace ThirdPrize.Classes
{
    public sealed class Vote : IDisposable
    {
        public string UserId { get; set; }
        public string Votes { get; set; }

        private readonly SqlConnection _myConn = new SqlConnection();

        public void Dispose()
        {
            _myConn.Dispose();
        }

        public Vote()
        {
            _myConn.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            _myConn.Open();
        }

        public bool CastVote()
        {
            bool result = false;

            //http://localhost:2789/Apps/WBCX/vote.aspx?user=1234&votes=1-2-3-4
            string user = UserId;
            string votes = Votes;

            try
            {
                if (user != null && votes != null)
                {
                    string[] allVotes = votes.Split('-');


                    string strDel = String.Format(@"delete from Votes where UserId = '{0}'", user);

                    using (var myCom1 = new SqlCommand(strDel, _myConn))
                    {
                        myCom1.ExecuteNonQuery();
                    }

                    foreach (string oneVote in allVotes)
                    {

                        using (SqlCommand cmd = new SqlCommand())
                        {
                            string sql = "insert into Votes ";
                            sql += "values(@userid, @titleid, @datevoted)";
                            cmd.CommandText = sql;
                            cmd.Parameters.AddWithValue("@userid", user);
                            cmd.Parameters.AddWithValue("@titleid", int.Parse(oneVote));
                            cmd.Parameters.AddWithValue("@datevoted", Convert.ToDateTime(DateTime.Now));
                            cmd.Connection = _myConn;
                            //_myConn.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                    _myConn.Close();
                }
                result = true;

            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
    }
}